package com.aop.example.interceptor;

import com.aop.example.aspect.RedisEnum;
import com.aop.example.util.JwtUtil;
import com.aop.example.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handle){

        String token = request.getHeader("Authorization");
        String redisToken = redisTemplate.opsForValue().get(RedisEnum.Login_TOKEN_KEY.getPrefix() + token);
        if(redisToken == null){
            return false;
        }
        Map<String, Object> claims = JwtUtil.parseToken(token);
        System.out.println(claims);
        //将业务数据放到ThreadLocal中
        ThreadLocalUtil.set(claims);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object Handle, Exception exception){
        ThreadLocalUtil.remove();
    }


}
